/*
 * @Author: blak-kong
 * @Date: 2019-12-02 09:46:34
 * @Email: 546598185@qq.com
 */
const path = require('path')
const fs = require('fs')
const Koa = require('koa');
const app = new Koa()
// 跨域
const cors = require("koa2-cors")
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const koaStatic = require('koa-static');
const logger = require('koa-logger')
const morgan = require('koa-morgan')

const mongoose = require('mongoose');
const passport = require('koa-passport');

// 引入users.js
const users = require('./routes/users');
const nav = require("./routes/nav")
const devServe = require("./routes/devServe")
const upload = require("./routes/upload")
const news = require("./routes/news")
const about = require("./routes/about")
const slideshow = require("./routes/slideshow")
const recommend = require("./routes/recommend")


// DB config
const db = require('./config/keys').mongoURI;

// 使用koa-bodyparser中间件
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))

//开启静态文件访问
app.use(koaStatic(
  path.resolve(__dirname, 'public')  
));

app.use(json())
app.use(logger())

const ENV = process.env.NODE_ENV
if (ENV !== 'production') {
  // 开发环境
  app.use(morgan('dev'));
} else {
  // 生产环境
  const logFileName = path.join(__dirname, 'logs', 'access.log')
  const writeStream = fs.createWriteStream(logFileName, {
    flags: 'a'
  })
  app.use(morgan('combined', {
    stream: writeStream
  }));
}

// error handler
onerror(app)

// // 跨域 
app.use(
  cors({
      origin: function(ctx) { //设置允许来自指定域名请求
          const whiteList = [ //可跨域白名单
            'http://localhost:3002',
            'http://localhost:5001',
            'http://localhost:8080',
            'http://localhost:8888',
            'http://www.sprout-edu.com'
          ];
          let url = ctx.header.origin; 
          if(whiteList.includes(url)){
              return url //注意，这里域名末尾不能带/，否则不成功，所以在之前我把/通过substr干掉了
          }
          return 'http://localhost:8081' //默认允许本地请求3000端口可跨域
      },
      maxAge: 1800, //指定本次预检请求的有效期，单位为秒。
      credentials: true, //是否允许发送Cookie
      allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], //设置所允许的HTTP请求方法
      allowHeaders: ['Content-Type', 'Authorization', 'Accept'], //设置服务器支持的所有头信息字段
      // exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'] //设置获取其他自定义字段
  })
)

// Connect to mongodb
mongoose
  .connect(db).then()
  .catch(err => console.log(err));

// passport 初始化
app.use(passport.initialize());

require('./config/passport')(passport);


// 使用routes
app.use(nav.routes(), nav.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(upload.routes(), upload.allowedMethods())
app.use(devServe.routes(), devServe.allowedMethods())
app.use(news.routes(), news.allowedMethods())
app.use(about.routes(), about.allowedMethods())
app.use(slideshow.routes(), slideshow.allowedMethods())
app.use(recommend.routes(), recommend.allowedMethods())


// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app